package com.group.util;

import com.group.model.Student;
import com.group.controller.StudentController;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * @author lenovo
 */
public class ExcelExportUtil {

    public static void exportToExcel(String filePath) throws Exception {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("成绩表");

        // 表头
        String[] headers = {"学号", "姓名", "性别", "生日", "Math", "Java", "PE", "总分"};
        Row headerRow = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            headerRow.createCell(i).setCellValue(headers[i]);
        }

        //  获取并按总成绩降序排列学生
        List<Student> sortedList = new ArrayList<>(StudentController.getAll());
        sortedList.sort((s1, s2) -> Double.compare(
                getTotalScore(s2), getTotalScore(s1))
        );

        int rowIndex = 1;
        for (Student s : sortedList) {
            Row row = sheet.createRow(rowIndex++);
            row.createCell(0).setCellValue(s.getId());
            row.createCell(1).setCellValue(s.getName());
            row.createCell(2).setCellValue(s.getGender());
            row.createCell(3).setCellValue(s.getBirth());

            Map<String, Double> scores = s.getScores();
            double math = scores.getOrDefault("Math", 0.0);
            double java = scores.getOrDefault("Java", 0.0);
            double pe = scores.getOrDefault("PE", 0.0);
            double total = math + java + pe;

            row.createCell(4).setCellValue(math);
            row.createCell(5).setCellValue(java);
            row.createCell(6).setCellValue(pe);
            row.createCell(7).setCellValue(total);
        }

        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            workbook.write(fos);
        }
        workbook.close();
    }

    private static double getTotalScore(Student s) {
        Map<String, Double> scores = s.getScores();
        return scores.getOrDefault("Math", 0.0)
                + scores.getOrDefault("Java", 0.0)
                + scores.getOrDefault("PE", 0.0);
    }
}


